<template>
  <div>
    <search-form
      :search-config="searchConfig"
      :label-width="150"
      @clear="clearSearch"
      @search="handleSearch"
    />
    <table-box
      ref="refTable"
      table-size="mini"
      :table-config="tableConfig"
      show-selection
      dragable
      :selected-arry.sync="tableSelected"
      :other-filters="otherFilters"
      @btnOperate="btnOperate"
      @selection-change="selectionChangeHandle"
    />
    <el-image-viewer
      v-if="showViewer"
      :on-close="closeViewer"
      :url-list="urlList"
    />
  </div>
</template>
<script>
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
import { saveAs } from 'file-saver'
import { deletFileData, downloadFile } from '@/api/common.js'
import { nowTime } from '@/utils/tool'
const JSZip = require('jszip')
export default {
  name: 'FileManage',
  components: { ElImageViewer },

  data() {
    return {
      tableSelected: [],
      // otherFilters: [],
      otherFilters: [],
      urlList: [],
      showViewer: false,
      nowTime,
      searchConfig: [
        { label: '门店建设项目号', prop: 'constCode', type: 'text', placeholder: '', filter: true },
        { label: '附件类型', prop: 'attachmentType', type: 'text', placeholder: '', filter: true },
        { label: '附件格式', prop: 'typeName', type: 'text', placeholder: '', filter: true }
      ],
      tableConfig: {
        interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/shopAttachment/page`,
        buttonGroupCode: 'default',
        hideSearchBar: true,
        tabIndex: 0,
        pageSize: 10,
        order: 'desc',
        sort: 'createTime',
        // 表格字段动态配置
        setting: [
          {
            prop: 'attachmentName',
            label: '附件名称',
            minWidth: '120'
          },
          {
            prop: 'attachmentType',
            label: '附件类型',
            minWidth: '120'
          },
          {
            prop: 'typeName',
            label: '附件格式',
            minWidth: '140'
          },
          {
            prop: 'createBy',
            label: '上传人',
            minWidth: '140'
          },
          {
            prop: 'createTime',
            label: '上传时间',
            minWidth: '140'
          },
          {
            prop: 'dr',
            label: '是否有效',
            minWidth: '90',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'BOOLEANS'
            }
          },
          {
            label: '操作',
            button: [
              {
                name: '预览',
                clickFun: this.previewFile,
                className: 'table-handelclick-text',
                type: 'text'
              },
              {
                name: '删除',
                clickFun: this.handleDelete,
                className: 'table-handelclick-text',
                type: 'text'
              }
            ]
          }
        ],
        btnList: !this.isProduction ? [{
          buttonName: '批量下载',
          outerFlag: true,
          optCode: 'download'
        }] : null
      }
    }
  },
  computed: {},
  async  created() {
  },
  methods: {
    // 关闭查看器
    closeViewer() {
      this.showViewer = false
      this.urlList = []
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该附件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用接口执行删除
        deletFileData(row.id).then(res => {
          if (res.success === 1) {
            this.$message({
              message: res.msg || '删除成功',
              type: 'success'
            })
            this.refreshTable()
          }
        })
      }).catch(() => {})
    },
    previewFile(file) {
      this.urlList = []
      const typeName = file.attachmentUrl.substring(file.attachmentUrl.lastIndexOf('.') + 1).toLowerCase()
      if (typeName === 'jpg' || typeName === 'jpeg' || typeName === 'png') {
      // 图片预览
        this.showViewer = true
        const picUrl = process.env.VUE_APP_IMG_PREFIX + '/' + file.attachmentUrl
        this.urlList.push(picUrl)
      } else if (typeName === 'pdf' || typeName === 'doc' || typeName === 'docx' || typeName === 'xlsx' || typeName === 'xls') {
        window.open(`${process.env.VUE_APP_OFFICE_PREFIX}?src=` + process.env.VUE_APP_IMG_PREFIX + file.attachmentUrl)
      } else {
        this.$message.warning('该文件类型不支持预览')
      }
    },
    selectionChangeHandle(data) {
      this.tableSelected = data
    },
    // 清空搜索数据
    clearSearch() {
    },
    // 获取搜索条件
    handleSearch(data) {
      this.otherFilters = [...data.filtersRaw]
      this.$nextTick(() => {
        this.$refs.refTable.initTableData()
      })
    },
    // 设置表格多选行高亮
    tableRowClassName({ row, rowIndex }) {
      const filterArr = this.tableSelected.filter(item => item.id === row.id)
      return filterArr.length > 0 ? 'selected-highlight' : ''
    },
    refreshTable(flag) {
      this.$refs.refTable.initTableData(!!flag)
    },
    getFile(url) {
      return new Promise((resolve, reject) => {
        downloadFile(url).then((res) => {
          resolve(res)
        }).catch((error) => {
          reject(error)
        })
      })
    },

    getFiles(data = []) {
      const zip = new JSZip()
      const promises = [] // 用于存储多个promise
      data.forEach((item) => {
        const promise = this.getFile(item.attachmentUrl).then((res) => {
          const fileName = item.attachmentName
          zip.file(fileName, res, { binary: true })
        })
        promises.push(promise)
      })
      const fileName = 'slm附件' + this.nowTime('download')
      Promise.all(promises).then(() => {
        zip.generateAsync({
          type: 'blob',
          compression: 'DEFLATE', // STORE：默认不压缩 DEFLATE：需要压缩
          compressionOptions: {
            level: 9 // 压缩等级1~9    1压缩速度最快，9最优压缩方式
          }
        }).then((res) => {
          saveAs(res, fileName || '附件.zip') // 利用file-saver保存文件
        })
      })
    },
    downloadFn() {
      if (this.tableSelected.length === 1) {
        const a = document.createElement('a')
        const url = `/pdf-file/` + this.tableSelected[0].attachmentUrl
        a.href = url
        a.download = this.tableSelected[0].attachmentName
        a.click()
        return
      }
      this.getFiles(this.tableSelected)
    },
    btnOperate(flag) {
      switch (flag) {
        case 'download':
          if (!this.singleJudge(this.tableSelected, '下载', false)) {
            return
          }
          this.$message('附件正在下载,请勿重复操作')
          this.downloadFn()
          break

        default:
          break
      }
    }
  }
}
</script>
